﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


public class SyncContainer<T>where T: ISyncItem
{
    Action _onCompleted;
    Action _onItemCompleted;
    List<T> items=new List<T>();
    int comleteCount;
    public SyncContainer(Action onCompleted, Action onItemCompleted)
    {
        _onCompleted += onCompleted;
        _onItemCompleted += onItemCompleted;
    }

    public void SetCompletedAction(Action onCompleted)
    {
        _onCompleted += onCompleted;
    }

    public void Add(T item)
    {
        item.OnItemCompleted += OnItemCompleted;
        items.Add(item);
    }

    public void Break()
    {
        for (int i = 0; i < items.Count; i++)
        {
            items[i].Break();
        }
        AllCompleted();
    }

    public void OnItemCompleted()
    {
        comleteCount++;
        if (_onItemCompleted!=null)
        {
            _onItemCompleted();
        }
        if (comleteCount == items.Count)
        {
            AllCompleted();
        }
    }

    public void AllCompleted()
    {
        comleteCount = 0;
        if (_onCompleted != null)
        {
            _onCompleted();
        }
    }

    public void Do()
    {
        for (int i = 0; i < items.Count; i++)
        {
            items[i].Do();
        }
    }

    public void Reset()
    {
        for (int i = 0; i < items.Count; i++)
        {
            items[i].OnItemCompleted -= OnItemCompleted;
        }
        items.Clear();
        _onCompleted = null;
    }
}